package com.example.controller;

import com.example.common.R;
import com.example.domain.LoginUser;
import com.example.domain.User;
import com.example.domain.UserDto;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin("http://localhost:8080")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public R<Map<String,String>> login(@RequestBody User user,HttpServletRequest httpServletRequest){
        //进行用户认证
        //通AuthenticationManager的实现类里的方法获取到前面UserDetailsImpl返回的loginUser里的账号密码进行匹对
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(user.getEmail(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(upat);
        //判断认证是否通过
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        LoginUser loginUser  = (LoginUser) authenticate.getPrincipal();
        String jwt = JwtUtil.createJWT(loginUser.getUser().getId());
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        map.put("userName",loginUser.getUser().getUserName());
        map.put("userLimit",loginUser.getUser().getUserLimit().toString());
        map.put("id",loginUser.getUser().getId());
        httpServletRequest.getSession().setAttribute("user",loginUser);
        httpServletRequest.getSession().setAttribute("token",jwt);
        System.out.println(httpServletRequest.getSession().getAttribute("user"));
        return R.success(map);
    }
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清除session
        if (request.getSession().getAttribute("user") != null){
            request.getSession().removeAttribute("user");
        }
        if (request.getSession().getAttribute("token") != null){
           request.getSession().removeAttribute("token");
        }
        return R.success("退出成功");
    }
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('article')")
    public R<List<User>> list(@RequestBody List<String> users){
        List<User> list = userService.list(users);
        return R.success(list);
    }
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('article')")
    public R<User> getOne (@PathVariable String id){
        User user = userService.getOne(id);
        return R.success(user);
    }
    @PostMapping("/register")
    public R<String> reg(@RequestBody UserDto user,HttpServletRequest request){
        Object code = request.getSession().getAttribute("code");
        if (!code.toString().equals(user.getCode())){
            return R.error("验证码错误");
        }
        userService.register(user);
        return R.success("注册成功");
    }
    @GetMapping("/sendCode/{email}")
    public R<String> send(@PathVariable String email,HttpServletRequest request){
        String s = sendCode(email);
        request.getSession().setAttribute("code",s);
        return R.success("成功");
    }
    @GetMapping("/randomUser")
    @PreAuthorize("hasAuthority('article')")
    public R<List<User>> randomUser(){
        List<User> users = userService.randomUser();
        return R.success(users);
    }

    public String sendCode(String email){
        final String yzm = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
        String code = "";
        Random r = new Random();
        //随机取5个
        for (int i = 0; i < 5; i++) {
            int index = r.nextInt(yzm.length());
            code = code + yzm.charAt(index);
        }
        MimeMessage mimeMessage = null;
        MimeMessageHelper helper = null;
        try {
            mimeMessage = javaMailSender.createMimeMessage();
            helper= new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("注册账号验证码");
            helper.setText("<p>您当前正在进行账号注册</p>\n" + "<p>您的验证码为:&ensp;" + code +
                    "</p>",true);
            //设置发送的邮箱
            helper.setTo(email);
            //发送方邮箱
            helper.setFrom("2855291304@qq.com");
            try {
                javaMailSender.send(mimeMessage);
            }catch (Exception e){
                throw  new RuntimeException("发送失败");
            }
        } catch (Exception e){
            throw  new RuntimeException("发送失败");
        }
        return code;
    }
}
